package twentytwenty;

/**
 * @Author: Spider Man
 * @Description: 14.最长公共前缀
 * @Date Created in 2020-09-21 10:13
 * @Modified By:
 */
public class LongestCommonPrefix_14 {
    public static void main(String[] args) {
        String[] strs = new String[]{"dog","racecar","car"};
        System.out.println(longestCommonPrefix(strs));
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0){
            return "";
        }
        StringBuilder common = new StringBuilder();
        String result = strs[0];
        for (int i = 1; i < strs.length; i++) {
            int len1 = result.length();
            int len2 = strs[i].length();
            for (int j = 0; j <= len2; j++) {
                if (j < len2 && j < len1 && strs[i].charAt(j) == result.charAt(j)){
                    common.append(strs[i].charAt(j));
                }else {
                    result = String.valueOf(common);
                    common.delete(0,j);
                    break;
                }
            }
        }
        return result;
    }
}
